#include "D3D9Renderer.h"
#include "color.h"

namespace sol9
{
namespace graphics
{

	__implementBaseClass(IRenderer);
	__implementClass(D3D9Renderer, IRenderer);

	D3D9Renderer::D3D9Renderer(HWND hDeviceWnd, const SRendererParameters& Params)
		: m_pD3D(nullptr), m_pD3DDevice(nullptr), m_hWnd(hDeviceWnd)
		, m_Parameters(Params)
	{
		initialize();
	}

	D3D9Renderer::~D3D9Renderer()
	{
		if (m_pD3DDevice)
		{
			m_pD3DDevice->Release();
			m_pD3DDevice = nullptr;
		}

		if (m_pD3D)
		{
			m_pD3D->Release();
			m_pD3D = nullptr;
		}
	}

	bool D3D9Renderer::initialize()
	{
		m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);

		if (!m_pD3D)
			return false;

		D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS));
		d3dpp.hDeviceWindow					= m_hWnd;
		d3dpp.BackBufferWidth				= m_Parameters.nWindowSize.width;
		d3dpp.BackBufferHeight				= m_Parameters.nWindowSize.height;
		d3dpp.BackBufferFormat				= D3DFMT_UNKNOWN;
		d3dpp.BackBufferCount				= 1;
		d3dpp.MultiSampleType				= D3DMULTISAMPLE_NONE;
		d3dpp.MultiSampleQuality			= 0;
		d3dpp.Windowed						= !m_Parameters.bFullscreen;
		d3dpp.FullScreen_RefreshRateInHz	= D3DPRESENT_RATE_DEFAULT;
		d3dpp.SwapEffect					= D3DSWAPEFFECT_DISCARD;
		d3dpp.AutoDepthStencilFormat		= D3DFMT_D24S8;
		d3dpp.EnableAutoDepthStencil		= TRUE; 
		d3dpp.PresentationInterval			= NULL;
		d3dpp.Flags							= 0;

		HRESULT result;
		result = m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hWnd,
						D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &m_pD3DDevice);

		return SUCCEEDED(result);
	}

	bool D3D9Renderer::beginScene(color cColor)
	{
		if (!m_pD3DDevice)
			return false;

		m_pD3DDevice->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, cColor.argb, 1.0f, 0);
		m_pD3DDevice->BeginScene();

		return true;
	}

	bool D3D9Renderer::endScene()
	{
		if (!m_pD3DDevice)
			return false;

		m_pD3DDevice->EndScene();
		m_pD3DDevice->Present(nullptr, nullptr, nullptr, nullptr);

		return true;
	}

} // namespace graphics
} // namespace sol9